﻿using AbpApplication.Expand;
using AbpEntityFrameworkcore.DbContext;
using AbpToDomain.EntityInfo;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NStandard;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using AbpApplication.InPut;
using Application.Expand;
using SignalR.Client;
using Microsoft.AspNetCore.SignalR.Client;
using SingalR.Client;

namespace AbpApplication.AppServices
{
    ///<inheritdoc/>
    public class BaseService : ApplicationService, IBaseService
    {

        private readonly IRepository<Box> Box_res;
        private readonly IRepository<BoxGrid> BoxGrid_res;
        private readonly IRepository<NeetOutMaterial> NeetOutMaterial_res;
        private readonly IRepository<TaskOrder> TaskOrder_res;
        private readonly IRepository<Warehouse> Warehouse_res;
        private readonly IRepository<WarehouseLine> WarehouseLine_res;
        private readonly IRepository<MaterialBase> MaterialBase_res;
        private readonly IRepository<Inlethouse> Inlethouse_res;
        private readonly IRepository<InlethouseLine> Inlethouseline_res;
        private readonly IRepository<lognote> LogNote_res;
        private readonly IRepository<MaterialProperty> MaterialProperty_res;
        private readonly IRepository<BoxPosition> BoxPosition_res;
        private readonly IRepository<BoxType> BinType_res;
        private readonly MyDbContext context;
        private readonly ILoginHelper loginHelper;
        public BaseService(
            IRepository<Box> box_res,
            IRepository<BoxGrid> boxGrid_res,
            IRepository<Warehouse> warehouse_res,
            IRepository<WarehouseLine> warehouseLine_res,
            IRepository<MaterialBase> materialBase_res,
            MyDbContext context,
            IRepository<NeetOutMaterial> neetOutMaterial_res,
            IRepository<Inlethouse> inlethouse_res,
            IRepository<InlethouseLine> inlethouseline_res,
            IRepository<TaskOrder> taskOrder_res,
            ILoginHelper loginHelper,
            IRepository<lognote> logNote_res,
            IRepository<MaterialProperty> materialProperty_res,
            IRepository<BoxPosition> boxPosition_res,
            IRepository<BoxType> binType_res)
        {
            Box_res = box_res;
            BoxGrid_res = boxGrid_res;
            Warehouse_res = warehouse_res;
            WarehouseLine_res = warehouseLine_res;
            MaterialBase_res = materialBase_res;
            this.context = context;
            NeetOutMaterial_res = neetOutMaterial_res;
            Inlethouse_res = inlethouse_res;
            Inlethouseline_res = inlethouseline_res;
            TaskOrder_res = taskOrder_res;
            this.loginHelper = loginHelper;
            LogNote_res = logNote_res;
            MaterialProperty_res = materialProperty_res;
            BoxPosition_res = boxPosition_res;
            BinType_res = binType_res;
        }


        public async Task<ApiResponse> CreateMaterialBase(InPut_BaseService7 inPut)//新料入库
        {
            try
            {
               // var boxgrids = await BoxGrid_res.WithDetailsAsync();
               // BoxGrid boxGrid = new BoxGrid();
               // boxGrid = await boxgrids.FirstOrDefaultAsync(x => x.BoxGridCode.Contains(inPut.BoxCode) && x.materialBase == null);
               // if (boxGrid == null) return new ApiResponse("该格口无储位可用", false, null);
               //  bool res=   await boxgrids.AnyAsync(x=>x.TheBox.BoxCode==inPut.BoxCode&&x.materialBase.MaterialProperty.MaterialProertyname==inPut.MaterialProertyName);
               // if(res)
               // {
               //     return new ApiResponse("相同物料不能放在同一个箱子", false, null);
               // }
               // if (boxGrid.TheBox.WarehouseLine != null) return new ApiResponse("该料箱当前在货仓中,无法新增料", false, null);
               // var MaterialBases = await MaterialBase_res.WithDetailsAsync();
               // MaterialBase materialBaseJudge = await MaterialBases.FirstOrDefaultAsync(x => x.MaterialCode == inPut.MaterialCode && x.BoxGrid != null);
               // if (materialBaseJudge != null) return new ApiResponse("已存在物料", false, null);
               // MaterialProperty materialProperty = await MaterialProperty_res.FirstOrDefaultAsync(x => x.MaterialProertyname == inPut.MaterialProertyName);
               //if (materialProperty == null)
               // {
               //     return new ApiResponse("物料属性不存在", false, null);
               // }

               // #region  operate
               // //creater materialbase 
               // MaterialBase materialBaseModel = await MaterialBases.FirstOrDefaultAsync(x => x.MaterialCode == inPut.MaterialCode && x.BoxGrid == null);
               // MaterialBase materialBase = new MaterialBase();
               // if (materialBaseModel == null)
               // {
               //     materialBase = materialBase.AddMaterialBase(inPut.Quantity,  inPut.MaterialCode, inPut.MaterialProertyName, boxGrid, materialProperty);
               //     await MaterialBase_res.InsertAsync(materialBase);
               //     boxGrid.materialBase = materialBase;
               // }
               // else
               // {
               //     materialBaseModel.Quantity = inPut.Quantity;
               //     materialBaseModel.MaterialProperty=materialProperty;
               //     await MaterialBase_res.UpdateAsync(materialBaseModel);
               //     boxGrid.materialBase = materialBaseModel;
               // }
               // //update boxgrid        
               // await BoxGrid_res.UpdateAsync(boxGrid);
                return new ApiResponse("加入料盒成功", true, null);
              
            }
            catch (Exception ex)
            {

                loginHelper.LoginAsync(inPut, "CreateMaterialBase");
                return new ApiResponse("内部错误服务器-CreateMaterialBase", false, null);
            }

        }
        public async Task<ApiResponse> CreateNeetOutMaterial(InPut_BaseService10 InPut)//手动出库-添加需出料-添加agv任务
        {
            try
            {
                //InPut.MaterialCodes = InPut.MaterialCodes.Distinct().ToList();
                ////List<MaterialBase> materialBases = await MaterialBase_res.GetListAsync(x =>InPut. MaterialCodes.Any(y => y == x.MaterialCode));
                //List<MaterialBase> materialBases = MaterialBase_res.WithDetails().ToList();
                //List<NeetOutMaterial> NeetOutMaterials = await NeetOutMaterial_res.GetListAsync(x => InPut.MaterialCodes.Any(y => y == x.Material.MaterialCode));
                //List<string> MaterialCodesDel = NeetOutMaterials.Select(x => x.Material.MaterialCode).ToList();
                //InPut.MaterialCodes = InPut.MaterialCodes.Except(MaterialCodesDel).ToList();
                //materialBases = materialBases.Where(x => InPut.MaterialCodes.Any(y => y == x.MaterialCode)).ToList();
                ////var taskOrders = await TaskOrder_res.GetListAsync(x => materialBases.Any(y => y.Info== x.Box.BoxCode));
                //List<TaskOrder> taskOrders = await TaskOrder_res.WithDetails().ToListAsync();
                //taskOrders = taskOrders.Where(x => materialBases.Any(y => y.BoxGrid.TheBox.BoxCode == x.Box.BoxCode && x.Type == "出库")).ToList();
                //List<TaskOrder> taskOrderLussed = taskOrders.Where(x => x.State == "已下发").ToList();
                //if (taskOrderLussed.Count > 0)
                //{
                //    return new ApiResponse(taskOrders[0].Box.BoxCode + "已发送AGV任务,无法再次添加出库", false, null);
                //}
                //#region operate
                ////creater neetOutMaterial
                ////List<NeetOutMaterial> neetOutMaterials = new List<NeetOutMaterial>();
                ////foreach (var materialBase in materialBases)
                ////{
                ////    NeetOutMaterial neetOutMaterial = new NeetOutMaterial();
                ////    neetOutMaterial = neetOutMaterial.AddNeetOutMaterial(materialBase, null, null, null, null, null);
                ////    neetOutMaterials.Add(neetOutMaterial);
                ////    materialBase.NeetOutMaterials.Add(neetOutMaterial);
                ////}
                ////await NeetOutMaterial_res.InsertManyAsync(neetOutMaterials);
                ////await MaterialBase_res.UpdateManyAsync(materialBases);
                ////creater taskorder
                //materialBases = materialBases.DistinctBy(x => x.BoxGrid.TheBox.BoxCode).ToList();
                //List<TaskOrder> taskOrderNotfinsih = taskOrders.Where(x => x.State == "未下发").ToList();
                //materialBases = materialBases.Where(x => !taskOrderNotfinsih.Any(y => y.Box.BoxCode == x.BoxGrid.TheBox.BoxCode)).ToList();//去掉已在任务中有的箱盒
                //foreach (var item in materialBases)
                //{
                //    TaskOrder taskOrder = new TaskOrder();
                //    taskOrder = taskOrder.AddTaskOrder("出库", item.BoxGrid.TheBox, item.BoxGrid.TheBox.WarehouseLine.WarehouseLineCode, InPut.InlethouseCode, null,null,null);
                //    item.BoxGrid.TheBox.TaskOrder = taskOrder;
                //    await Box_res.UpdateAsync(item.BoxGrid.TheBox);
                //    await TaskOrder_res.InsertAsync(taskOrder);
                //}
                //return new ApiResponse("已添加至需出料", true, null);
                //#endregion


                return new ApiResponse("ss", false, null);
            }
            catch (Exception ex)
            {

                loginHelper.LoginAsync(InPut, "CreateNeetOutMaterial");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
   
        public async Task<ApiResponse> Create_Inlethouse(InPut_BaseService9 input)
        {
            try
            {

                bool result = await Inlethouseline_res.AnyAsync(x => x.Xaxis == input.Xaxis && x.Yaxis == input.Yaxis && x.Zaxis == input.Zaxis);
                if (result) return new ApiResponse("入出.库口已存在", false, null);
                Inlethouse inlethouse = new Inlethouse();
                inlethouse = inlethouse.AddInlethouse(input.InlethouseCode, input.Xaxis, input.Yaxis, input.Zaxis, input.InlethouseName, input.parameter);
                InlethouseLine inlethouseLine = new InlethouseLine();
                inlethouseLine = inlethouseLine.AddInlethouseline(input.Long, input.Wide, input.high, input.Xaxis, input.Yaxis, input.Zaxis, null, input.Type);
                inlethouseLine.InlethouseLineCode = input.InlethouseCode + "-" + input.Xaxis.ToString("D2") + "-" + input.Yaxis.ToString("D2") + "-" + input.Zaxis.ToString("D2");
                inlethouseLine.TheInlethouse = inlethouse;
                inlethouse.inlethouselines.Add(inlethouseLine);
                await Inlethouse_res.InsertAsync(inlethouse);
                await Inlethouseline_res.InsertAsync(inlethouseLine);
                return new ApiResponse("配置成功", true, null);
            }
            catch (Exception ex)
            {


                loginHelper.LoginAsync(input, "Create_Inlethouse");
                return new ApiResponse("内部错误服务器", false, null);
            }

        }//配置入库口
        public async Task<ApiResponse> CreateLog(InPut_BaseService15 InPut)//添加日志
        {
            lognote lognote = new lognote();
            lognote.DateTime = DateTime.Now;
            lognote.User = InPut.User;
            lognote.Type = InPut.Type;
            lognote.Note = InPut.Note;
            lognote.BoxCode = InPut.BoxCode;
            lognote.MaterialCode = InPut.MaterialCode;
            lognote.MaterialName = InPut.MaterialName;
            lognote.OrderNo = InPut.OrderNo;
            if (InPut.Type == "入库" || InPut.Type == "出库")
            {
               MaterialBase materialBase= await context.materialBases.Where(x=>x.MaterialName==InPut.MaterialName).FirstOrDefaultAsync();
               lognote.Definition = materialBase.MaterialCode;
            }
            else
            {
                lognote.Definition = InPut.Definition;
            }
           
            lognote.Batch = InPut.Batch;
            lognote.Size = InPut.Size;
            lognote.WarehouseLineCode = InPut.WarehouseLineCode;
            await LogNote_res.InsertAsync(lognote);
            return new ApiResponse("添加成功", true, null);
        }
        public async Task<ApiResponse> Update_Box(InPut_BaseService2 input)//更改箱盒
        {
            try
            {
                //var boxs = await Box_res.WithDetailsAsync();
                //Box box=await  boxs.FirstOrDefaultAsync(x=>x.BoxCode == input.BoxCode);
                //if (box==null) return new ApiResponse("未查询到料盒", false, null);
                //foreach (var item in box.BoxGrids)
                //{
                //    if (item.materialBase!=null)
                //    {
                //        return new ApiResponse("料盒中有物料不允许修改", false, null);
                //    }
                //}
                //box.BoxCode = input.BoxCode;
                //box.BoxGrids.Clear();
                //await Box_res.UpdateAsync(box);
                //List<BoxGrid> boxGrids = new List<BoxGrid>();
                //for (int i = 0; i < input.BoxGridQuantity; i++)
                //{
                //    BoxGrid boxGrid = new BoxGrid();
                //    string BoxGridCode = $"{box.BoxCode}_{(i + 1).ToString("D2")}";
                //    boxGrid = boxGrid.AddBoxGrid(i+ 1, BoxGridCode, box, 0);
                //    boxGrids.Add(boxGrid);
                //}
                //await BoxGrid_res.InsertManyAsync(boxGrids);
                //box.BoxGrids.AddRange(boxGrids);
                //box.BoxGridQuantity = (int)input.BoxGridQuantity;
                //await Box_res.UpdateAsync(box);
                return new ApiResponse("更新成功", true, null);
                //var boxs = await Box_res.WithDetailsAsync();
                //foreach (var boxcode in input.BoxCode)
                //{
                //    Box box = boxs.FirstOrDefault(x => x.BoxCode == boxcode);
                //    if (box == null)
                //    {
                //        return new ApiResponse("未查询到", false, null);
                //    }                
                //    box.BoxGrids .Clear();
                //    await Box_res.UpdateAsync(box);
                //    await UnitOfWorkManager.Current.SaveChangesAsync();

                //    List<BoxGrid> boxGrids = new List<BoxGrid>();
                //    for (int i = 0; i < input.BoxGridQuantity; i++)
                //    {
                //        BoxGrid boxGrid = new BoxGrid();
                //        string BoxGridCode = $"{box.BoxCode}_{(i + 1).ToString("D2")}";
                //        boxGrid = boxGrid.AddBoxGrid(i + 1, BoxGridCode, box);              
                //        boxGrids.Add(boxGrid);

                //    }
                //    await BoxGrid_res.InsertManyAsync(boxGrids);
                //    box.BoxGrids.Clear();
                //    box.BoxGrids.AddRange(boxGrids);
                //    box.BoxGridQuantity = (int)input.BoxGridQuantity;
                //    await Box_res.UpdateAsync(box);

                //}
                //return new ApiResponse("更新成功", true, null);

            }
           catch (Exception ex)
            {              
                loginHelper.LoginAsync(input, "Update_Box");
                return new ApiResponse("内部服务器错误", false,null);
            }


        }      
        public async Task<ApiResponse> Update_WarehouseLines(InPut_BaseService5 inPut)//更新仓位状态
        {
            try
            {
                foreach (var item in inPut.WarehouseLineCodes)
                {
                    WarehouseLine warehouseLine = await WarehouseLine_res.FirstOrDefaultAsync(x => x.WarehouseLineCode == item);
                    if (warehouseLine != null)
                    {
                        warehouseLine.IsEnable = inPut.Type;
                    }
                    await WarehouseLine_res.UpdateAsync(warehouseLine);
                }
                return new ApiResponse("修改成功", true, null);

            }
            catch(Exception ex)
            {              
                loginHelper.LoginAsync(inPut, "Update_WarehouseLines");
                return new ApiResponse("内部服务器错误", false, null);
            }



        }
        public async Task<ApiResponse> UpdateTaskOrderState(InPut_BaseService11 InPut)//修改任务状态
        {
            try
            {
                TaskOrder taskOrder = await TaskOrder_res.FirstOrDefaultAsync(x => x.TaskOrderCode == InPut.TaskOrderCode);
                if (taskOrder == null)
                {
                    return new ApiResponse("未查询到单号", false, null);
                }
                taskOrder.State = InPut.Type;
                await TaskOrder_res.UpdateAsync(taskOrder);
                return new ApiResponse("修改成功", true, null);
            }
            catch (Exception ex)
            {


                loginHelper.LoginAsync(InPut, "UpdateTaskOrderState");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> GetList_InlethouesCode(string Type)
        {
            try
            {
                List<InlethouseLine> inlethouseLines=   await Inlethouseline_res.GetListAsync(x=>x.Type == Type);
                List<string> InlethouseCodes=inlethouseLines.Select(x=>x.InlethouseLineCode).ToList();
                return new ApiResponse("获取成功",true, InlethouseCodes);
            }
            catch (Exception ex)
            {
                Logger.LogWarning($"GetList_InlethouesCode-{Type}");

     
                return new ApiResponse("内部错误服务器", false, null);
            }
        }//获取出口
           
        public async Task<ApiResponse> DeleteBox(InPut_BaseService8 InPut)//删箱子
        {
            try
            {
                //List<Box> BoxDel = new List<Box>();
                //if (string.IsNullOrEmpty(InPut.EndBoxCode))
                //{
                //    BoxDel.Add(await Box_res.FirstOrDefaultAsync(x => x.BoxCode == InPut.BoxCode));
                //}
                //else
                //{
                //    List<Box> boxes=  await Box_res.GetListAsync();
                //    BoxDel = boxes.Where(x => int.Parse(x.BoxCode.Substring(x.BoxCode.Length - 4)) >=
                //                            int.Parse(InPut.BoxCode.Substring(InPut.BoxCode.Length - 4)) &&
                //                            int.Parse(x.BoxCode.Substring(x.BoxCode.Length -4)) <=
                //                            int.Parse(InPut.EndBoxCode.Substring(InPut.EndBoxCode.Length - 4))).ToList();
                //}
                //bool res= BoxDel.Any(x => x.BoxGrids.Any(y => y.materialBase != null));
                //if (res)
                //{
                //    return new ApiResponse("有物料,无法删除", false, null);
                //}
                //await Box_res.DeleteManyAsync(BoxDel);
                return new ApiResponse("删除成功", true, null);
            }
            catch (Exception ex)
            {

                loginHelper.LoginAsync(InPut, "DeleteBox");
                return new ApiResponse("内部错误服务器", false, null);
            }

        }
        public async Task<ApiResponse> test(InPut_EssService InPut)
        {
           await SingalrMethod.GetConnectionAsync();
      
            

            return new ApiResponse("未查询到在盒物料", false, null);
        }
        public async Task<ApiResponse> DeleteMaterial(InPut_BaseService4 input)//出料
        {
            try
            {
                //var materialBases = await MaterialBase_res.WithDetailsAsync();
                //MaterialBase materialBase = await materialBases.FirstOrDefaultAsync(x => x.MaterialProperty.MaterialProertyname== input.MaterialProertyName &&
                //x.BoxGrid.BoxGridCode.Contains(input.BoxCode));
                //if (materialBase == null) return new ApiResponse("未查询到在盒物料", false, null);
                //if (materialBase.BoxGrid.TheBox.WarehouseLine != null) return new ApiResponse("料盒未下架", false, null);
                //materialBase.Quantity=materialBase.Quantity-input.DelQutity;
                //if(materialBase.Quantity > 0)
                //{
                //    await MaterialBase_res.UpdateAsync(materialBase);
                //}
                //else
                //{
                //    await MaterialBase_res.DeleteAsync(materialBase);
                //}
                //lognote lognote = new lognote();
                //lognote.Type = "出库";
                //lognote.Note = "物料被取走了";
                //lognote.MaterialName=materialBase.MaterialName;
                //lognote.Size = input.DelQutity.ToString();
                //lognote.BoxCode = input.BoxCode;
                //lognote.Batch = materialBase.MaterialProperty.Unit;
                //lognote.User=input.User;
                //lognote.Definition=materialBase.MaterialProperty.Description;
                //lognote.DateTime=DateTime.Now;
                //await LogNote_res.InsertAsync(lognote);
                return new ApiResponse("取料成功,请取走物料", true, null);
            }catch(Exception ex)
            {
                loginHelper.LoginAsync(input, "DeleteMaterial");
                return new ApiResponse("内部错误服务器-DeleteMaterial", false, null);
            }
        }
        public async Task<ApiResponse> RemovesMaterial(List<string> MaterialCodes)//删料
        {
            try
            {
                List<MaterialBase> materialBases = await MaterialBase_res.GetListAsync(x => MaterialCodes.Any(y => y == x.MaterialCode));
                materialBases.ForEach(x => x.Id_BoxPosition = null);
                await MaterialBase_res.DeleteManyAsync(materialBases);
                return new ApiResponse("删除成功", true, null);
            }catch (Exception ex)
            {
                loginHelper.LoginAsync(MaterialCodes, "RemovesMaterial");
                return new ApiResponse("内部错误服务器-RemovesMaterial", false, null);
            }

        }
   
        public async Task<ApiResponse> UpdateMaterialBaserQuantity(InPut_BaseService7 inPut)//更新物料数量
        {
            try
            {
                //var MaterialBases = await MaterialBase_res.WithDetailsAsync();
                //MaterialBase materialBaseJudge = await MaterialBases.FirstOrDefaultAsync(x => x.MaterialProperty.MaterialProertyname == inPut.MaterialProertyName && x.BoxGrid.TheBox.BoxCode== inPut.BoxCode);
                //if (materialBaseJudge == null) return new ApiResponse("未查询到物料", false, null);
                //#region  operate
                ////update materialbase 
                //materialBaseJudge.Quantity = materialBaseJudge.Quantity+ inPut.Quantity;
                //await MaterialBase_res.UpdateAsync(materialBaseJudge);
                return new ApiResponse("更新成功", true, null);
          
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(inPut, "UpdateMaterialBaserQuantity");
                return new ApiResponse("内部错误服务器-UpdateMaterialBaserQuantity", false, null);
            }
        }
        public async Task<ApiResponse> CreateMaterialProperty(InPut_BaseService14 InPut)//添加物料属性
        {
            try
            {
                MaterialProperty materialProperty = new MaterialProperty();
                materialProperty.MaterialProertyname = InPut.MaterialProertyname;
                materialProperty.Description = InPut.Description;
                materialProperty.Unit = InPut.Unit;
                materialProperty.Type = InPut.Type;
                await MaterialProperty_res.InsertAsync(materialProperty);
                return new ApiResponse("添加成功", true, null);
            }
            catch(Exception ex)
            {
                loginHelper.LoginAsync(InPut, "CreateMaterialProperty");
                return new ApiResponse("内部错误服务器-CreateMaterialProperty", false, null);
            }
        }


        //使用中

        public async Task<ApiResponse> Create_Warehouses(InPut_BaseService3 input)//配置库位
        {
            try
            {
                bool res = await Warehouse_res.AnyAsync(x => x.WarehouseName == input.WarehouseName);
                if (res)
                {
                    return new ApiResponse("库位名称重复", false, null);
                }
                BoxType binType=  await BinType_res.FirstOrDefaultAsync(x=>x.BoxType_Name == input.BinType_Name);
                if (binType == null)
                {
                    return new ApiResponse("查询不到的Bintype", false, null);
                }
                Warehouse warehouse = new Warehouse();
                warehouse = warehouse.AddWarehouse(input.WarehouseCode, input.Xaxis, input.Yaxis, input.Zaxis, input.WarehouseName, input.parameter, input.Type);
                await Warehouse_res.InsertAsync(warehouse);
                int sum = input.Xaxis * input.Yaxis * input.Zaxis;
                List<WarehouseLine> lines = new List<WarehouseLine>();
                //排
                for (int j = 1; j <= input.Xaxis; j++)
                {
                    //高
                    for (int k = 1; k <= input.Yaxis; k++)
                    {
                        //列
                        for (int y = 1; y <= input.Zaxis; y++)
                        {
                            WarehouseLine warehouseLine = new WarehouseLine();
                            warehouseLine = warehouseLine.AddWarehouseline(binType.Width, binType.Height,  binType.DePth, j, k, y, warehouse,binType);
                            warehouseLine.WarehouseLineCode = warehouse.WarehouseCode + "-" + j.ToString("D3") + "-" + k.ToString("D3") + "-" + y.ToString("D2");
                            lines.Add(warehouseLine);
                        }
                    }
                }
                warehouse.warehouselines.AddRange(lines);
                await Warehouse_res.InsertAsync(warehouse);
                await WarehouseLine_res.InsertManyAsync(lines);
                return new ApiResponse("配置成功", true, null);
            }
            catch (Exception ex)
            {
                loginHelper.LoginAsync(input, "Create_Warehouses");
                return new ApiResponse("内部错误服务器", false, null);
            }

        }
        public async Task<ApiResponse> Create_Inlethouses(InPut_BaseService9 input)//配置缓存货位
        {
            try
            {
                bool res = await Inlethouse_res.AnyAsync(x => x.InlethouseName == input.InlethouseName);
                if (res)
                {
                    return new ApiResponse("库位名称重复", false, null);
                }
                Inlethouse inlethouse = new Inlethouse();
                inlethouse = inlethouse.AddInlethouse(input.InlethouseCode, input.Xaxis, input.Yaxis, input.Zaxis, input.InlethouseName, input.parameter);
                await Inlethouse_res.InsertAsync(inlethouse);
                int sum = input.Xaxis * input.Yaxis * input.Zaxis;
                List<InlethouseLine> lines = new List<InlethouseLine>();
                //排
                for (int j = 1; j <= input.Xaxis; j++)
                {
                    //高
                    for (int k = 1; k <= input.Yaxis; k++)
                    {
                        //列
                        for (int y = 1; y <= input.Zaxis; y++)
                        {
                            InlethouseLine inlethouseLine = new InlethouseLine();
                            inlethouseLine = inlethouseLine.AddInlethouseline(input.Long, input.Wide, input.high, j, k, y, inlethouse, input.Type);
                            inlethouseLine.InlethouseLineCode = inlethouse.InlethouseCode + "-" + j.ToString("D2") + "-" + k.ToString("D2") + "-" + y.ToString("D2");
                            lines.Add(inlethouseLine);
                        }
                    }
                }
                inlethouse.inlethouselines.AddRange(lines);
                await Inlethouse_res.InsertAsync(inlethouse);
                await Inlethouseline_res.InsertManyAsync(lines);
                return new ApiResponse("配置成功", true, null);
            }
            catch (Exception ex)
            {


                loginHelper.LoginAsync(input, "Create_Inlethouses");
                return new ApiResponse("内部错误服务器", false, null);
            }
        }
        public async Task<ApiResponse> Create_Boxs(InPut_BaseService input)//配置箱盒
        {
            try
            {

                bool res = await Box_res.AnyAsync(x => x.BoxCode.Substring(x.BoxCode.Length - 4) == input.StartNumber.ToString("D4") ||
                                                  x.BoxCode.Substring(x.BoxCode.Length - 4) == input.EndNumber.ToString("D4"));
                if (res)
                {
                    return new ApiResponse("箱盒已存在", false, null);
                }
                BoxType binType = await BinType_res.FirstOrDefaultAsync(x => x.BoxType_Name == input.BinType_Name);
                if (binType == null)
                {
                    return new ApiResponse("查询不到的Bintype", false, null);
                }
                //配置箱盒
                int boxquantity = input.EndNumber - input.StartNumber + 1;
                List<Box> boxes = new List<Box>();
                for (int i = 0; i < boxquantity; i++)//箱
                {
                    Box box = new Box();
                    string BoxCode = input.Name + "0000" + (input.StartNumber + i).ToString("D4");
                    box = box.AddBox(BoxCode, input.BoxGridQuantity, input.VirtualSpace,binType);
                    List<BoxGrid> boxGrids = new List<BoxGrid>();
                    for (int y = 0; y < input.BoxGridQuantity; y++)//格
                    {
                        //有虚拟货位
                        if (input.VirtualSpace)
                        {
                                BoxGrid boxGrid = new BoxGrid();
                                string BoxGridCode = $"{BoxCode}_{(y + 1)}";
                                boxGrid = boxGrid.AddBoxGrid(y + 1, BoxGridCode, box, input.PostionQuantity);
                                boxGrids.Add(boxGrid);
                            List<BoxPosition> boxPositions = new List<BoxPosition>();
                            for (int x = 1; x <= input.PostionQuantity; x++)
                            {
                                 BoxPosition boxPosition = new BoxPosition();
                                 string BoxPositionCode = $"{BoxGridCode}_{x}";
                                 boxPosition= boxPosition.AddBoxPosition(BoxPositionCode, boxGrid,x);
                                 boxPositions.Add(boxPosition);
                            }
                            await BoxPosition_res.InsertManyAsync(boxPositions);
                        }
                        //无虚拟货位
                        else
                        {
                            BoxGrid boxGrid = new BoxGrid();
                            string BoxGridCode = $"{BoxCode}_{(y + 1)}";
                            boxGrid = boxGrid.AddBoxGrid(y + 1, BoxGridCode, box, 0);
                            boxGrids.Add(boxGrid);
                        }

                    }
                    await BoxGrid_res.InsertManyAsync(boxGrids);
                    box.BoxGrids.AddRange(boxGrids);
                    boxes.Add(box);
                }
                await Box_res.InsertManyAsync(boxes);
                return new ApiResponse("生成成功", true, null);
            }
            catch (Exception ex)
            {


                loginHelper.LoginAsync(input, "Create_Boxs");
                return new ApiResponse("内部服务器错误", false, null);
            }
        }
        public async Task<ApiResponse> CreateTaskOrder(InPut_BaseService6 InPut)//添加agv入库任务
        {
            Box box = await context.boxs.Include(x => x.WarehouseLine).Include(x=>x.BinType). FirstOrDefaultAsync(x => x.BoxCode == InPut.BoxCode);
            if (box == null)
            {
                return new ApiResponse("未查询到箱盒", false, null);
            }
            if (box.WarehouseLine != null)
            {
                return new ApiResponse("箱盒已在货架上", false, null);
            }
            List<WarehouseLine> warehouseLines = await WarehouseLine_res.GetListAsync(x => x.Box == null && x.IsEnable == true && x.BinType == box.BinType && x.IsOccupy == false);
            if (warehouseLines.Count == 0)
            {
                return new ApiResponse("库位已用完", false, null);
            }
            WarehouseLine warehouseLine = warehouseLines.OrderBy(x => Random.Shared.Next()).First();

            var inlethouseLines = await Inlethouseline_res.WithDetailsAsync();
            InlethouseLine inlethouseLine =await inlethouseLines.FirstOrDefaultAsync(x => x.Box == null && x.IsEnable == true && x.IsOccupy == false && x.InlethouseLineCode.Contains( InPut.InletCode));
            if (inlethouseLine == null)
            {
                return new ApiResponse("缓存货架已用完", false, null);
            }
       
       
            bool res = await TaskOrder_res.AnyAsync(x => x.Id_Box == box.Id_Box);
            if (res) return new ApiResponse("已存在相同箱盒任务/或者任务还没结束,检查ESS任务系统去！！！", false, null);
            TaskOrder taskOrder = new TaskOrder();
            taskOrder.Box = box;
            taskOrder.Type = "入库";
            taskOrder.WarehouseCode = warehouseLine.WarehouseLineCode;
            taskOrder.InlethouseCode = inlethouseLine.InlethouseLineCode;
            taskOrder.CreatTime = DateTime.Now;
            taskOrder.State = "未下发";
            taskOrder.TaskOrderCode = ExtendRandom.CreateRandom();
            box.TaskOrder = taskOrder;
            await Box_res.UpdateAsync(box);
            await TaskOrder_res.InsertAsync(taskOrder);
            await UnitOfWorkManager.Current.SaveChangesAsync();
            warehouseLine.IsOccupy = true;
            await WarehouseLine_res.UpdateAsync(warehouseLine);
            inlethouseLine.IsOccupy = true;
            await Inlethouseline_res.UpdateAsync(inlethouseLine);
            return new ApiResponse("任务生成成功", true, inlethouseLine.InlethouseLineCode);
        }
        public async Task<ApiResponse> DeleteTaskOrder(List<string> TaskOrderCodes)
        {
            try
            {
                List<TaskOrder> taskOrders = await TaskOrder_res.GetListAsync(x => TaskOrderCodes.Any(y => y == x.TaskOrderCode));
                List<WarehouseLine> warehouseLines = await WarehouseLine_res.GetListAsync();
                warehouseLines = warehouseLines.Where(x => taskOrders.Any(y => y.WarehouseCode == x.WarehouseLineCode)).ToList();
                List<InlethouseLine> inlethouseLines= await Inlethouseline_res.GetListAsync();
                inlethouseLines=inlethouseLines.Where(x => taskOrders.Any(y => y.InlethouseCode == x.InlethouseLineCode)).ToList();
                List<Box>boxs=  await Box_res.GetListAsync();
                boxs = boxs.Where(x => taskOrders.Any(y => y.Id_Box == x.Id_Box)).ToList();
                bool res = taskOrders.Any(x => x.State != "未下发");
                if (res) { return new ApiResponse("只能删除未下发的任务", false, null); }
                await TaskOrder_res.DeleteManyAsync(taskOrders);
                if (taskOrders.All(x => x.Type == "入库"))
                {
                    warehouseLines.ForEach(x => x.IsOccupy = false);
                    await WarehouseLine_res.UpdateManyAsync(warehouseLines);
                }
                inlethouseLines.ForEach(x =>
                {
                    x.IsOccupy = false; 
                    x.Box = null;
                });
                boxs.ForEach(x =>
                {
                    x.InlethouseLine = null;
                });
     
                await Inlethouseline_res.UpdateManyAsync(inlethouseLines);
                await Box_res.UpdateManyAsync(boxs);
                loginHelper.LoginAsync(TaskOrderCodes, "删除了任务");
                return new ApiResponse("删除成功", true, null);
            }
            catch (Exception ex)
            {

                loginHelper.LoginAsync(TaskOrderCodes, "DeleteTaskOrder");
                return new ApiResponse("DeleteTaskOrder错误", false, null);
            }

        }//删除任务 
        public async Task<ApiResponse> CreateTaskOrderOut(InPut_BaseService13 InPut)//agv出库任务
        {
            try
            {
                List<TaskOrder> taskOrders = await TaskOrder_res.WithDetails().ToListAsync();
                List<TaskOrder> taskOrdersDel = taskOrders.Where(x => InPut.BoxCodes.Any(y => y == x.Box.BoxCode)).ToList();
                List<Box> boxes = await Box_res.WithDetails().ToListAsync();
                boxes = boxes.Where(x => InPut.BoxCodes.Any(y => y == x.BoxCode)).ToList();
                boxes = boxes.Where(x => !taskOrdersDel.Any(y => y.Id_Box == x.Id_Box)).ToList();
                bool res = boxes.Any(x => x.WarehouseLine == null);
                if (res)
                {
                    return new ApiResponse("有料盒不在货架上", false, null);
                }

               List<InlethouseLine> inlethouseLines=  await Inlethouseline_res.GetListAsync(x => x.InlethouseLineCode.Contains(InPut.InlethouseCode)&&x.IsOccupy==false);
                if (inlethouseLines.Count() < InPut.BoxCodes.Count())
                {
                    return new ApiResponse("目前缓存架可用位置不够", false, null);
                }
                List<TaskOrder> taskOrdersInsert = new List<TaskOrder>();

                int i = 0;
                foreach (var item in boxes)
                {
                    TaskOrder taskOrder = new TaskOrder();
                    taskOrder = taskOrder.AddTaskOrder("出库", item, item.WarehouseLine.WarehouseLineCode, inlethouseLines[i].InlethouseLineCode, null, null, null);
                    taskOrdersInsert.Add(taskOrder);
                    inlethouseLines[i].IsOccupy = true;
                    i++;
                }
                await TaskOrder_res.InsertManyAsync(taskOrdersInsert);
                await Inlethouseline_res.UpdateManyAsync(inlethouseLines);
                return new ApiResponse("任务生成成功", true, null);
            }
            catch (Exception ex)
            {


                loginHelper.LoginAsync(InPut, "CreateTaskOrderOut");
                return new ApiResponse("CreateTaskOrderOut错误", false, null);
            }
        }
        public async Task<ApiResponse> Create_Bintype(InPut_BaseService16 InPut)//配置bin
        {
            try
            {
                bool binTypeCheck = await BinType_res.AnyAsync(x => x.BoxType_Name == InPut.BinType_Name);
                if (binTypeCheck)
                {
                    return new ApiResponse("BinName重复", false, null);
                }
                BoxType binType = new BoxType();
                binType.BoxType_Name = InPut.BinType_Name;
                binType.DePth = InPut.DePth;
                binType.Width = InPut.Width;
                binType.Height = InPut.Height;
                await BinType_res.InsertAsync(binType);
                return new ApiResponse("添加Bintype成功", true, null);
            }
            catch (Exception ex)
            {


                loginHelper.LoginAsync(InPut, "Create_Bintype");
                return new ApiResponse("Create_Bintype-接口错误", false, null);
            }

        }
        public async Task<ApiResponse> Getlist_Bintypes()//获取bins
        {
           List<BoxType> binTypes=  await BinType_res.GetListAsync();
            return new ApiResponse("添加Bintype成功", true, binTypes);
        }
    }
}
